package com.fatgirl.callBackHandle
{
	import flash.events.EventDispatcher;

	/**
	 * 回调事件
	 * 作为返回值存在于函数后面
	 * @author iceman
	 * 
	 */
	public class CallBackEvent
	{
		private static var s_CallBackEventList:Array = new Array;
		private var m_callBacklist:Array = new Array;
		private var m_sequenceFunList:Array = new Array;
		public function CallBackEvent(_name:String)
		{
			if(!_name)throwError(this,FatError.VALUE_IS_NULL);
			if(s_CallBackEventList[_name]) throwError(this,FatError.SINGLETON_CLASS);
		}
		public static function getInstance(_name:String):CallBackEvent
		{
			if(!s_CallBackEventList[_name])s_CallBackEventList[_name] = new CallBackEvent(_name);
			return s_CallBackEventList[_name] as CallBackEvent;
		}
		/**
		 * 顺序执行函数，发现需要回调的退出，等待回调后再进行调用 
		 * @param _obj
		 * 
		 */
		public function sequenceFun(_obj:Object):void
		{
			while(m_sequenceFunList.length>0)
			{
				var t_fun:DimFun = m_sequenceFunList.shift() as DimFun;
				if(t_fun)
				{
					if(t_fun.callback!="")
					{
						if(t_fun.argsValueList.length)
							addCallBackEvent(t_fun.callback,t_fun.funName,t_fun.argsValueList);
						else addCallBackEvent(t_fun.callback,t_fun.funName,null);
						return;
					}
					var args:Array = t_fun.argsValueList;
					if(args.length)
					{
						(_obj[t_fun.funName] as Function).apply(null,args);
					}
					else
					{
						(_obj[t_fun.funName] as Function).call(null);
					}
				}
			}
		}
		/**
		 * 添加顺序函数链表 
		 * @param _funName
		 * @param args
		 * 
		 */
		public function addSequenceFun(_dimFun:DimFun):void
		{
			m_sequenceFunList.push(_dimFun);
		}
		private function addCallBackEvent(_callBackFunName:String,_funName:String,_args:Array):void
		{
			if(m_callBacklist[_callBackFunName])throwError(CallBackEvent,FatError.VALUE_IS_REPEAT);
			var t_CallBackItem:CallBackItem = new CallBackItem;
			t_CallBackItem.funName = _funName;
			t_CallBackItem.args = _args;
			m_callBacklist[_callBackFunName] = t_CallBackItem;
		}
		/**
		 * 回调函数，调用完继续执行顺序函数链表 
		 * @param _funName
		 * @param _obj
		 * 
		 */
		public function callEvent(_funName:String,_obj:Object):void
		{
			var t_callBaclItem:CallBackItem = m_callBacklist[_funName] as CallBackItem;
			if(t_callBaclItem)	
			{
				var t_funName:String = t_callBaclItem.funName;
				if(t_callBaclItem.args && t_callBaclItem.args.length)(_obj[t_funName] as Function).apply(null,t_callBaclItem.args);
				else (_obj[t_funName] as Function).apply(null);
				delete m_callBacklist[_funName];
				m_callBacklist[_funName] = null;
				sequenceFun(_obj);
			}
		}
	}
}
class CallBackItem
{
	public var funName:String;
	public var args:Array = new Array;
	public function CallBackItem()
	{
		
	}
}